<?php
$page_title = "修改密码";
session_start();
include 'template/header.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	require 'mysqli_connect.php';
	$errors = array();
	if (empty($_POST['email'])) {
		$errors[] = '未输入邮箱';
	} else {
		$em = mysqli_real_escape_string($dbc, $_POST['email']);
	}
	if (empty($_POST['pass'])) {
		$errors[] = '未输入密码';
	} else {
		$op = mysqli_real_escape_string($dbc, trim($_POST['pass']));
	}
	if (empty($_POST['pass1'])) {
		$errors[] = '未输入新密码';
	} else if (empty($_POST['pass2'])) {
		$errors[] = '请再次输入新密码以确认';
	} else if ($_POST['pass1'] != $_POST['pass2']) {
		$errors[] = '两次输入的新密码不一致';
	} else {
		// 保存密码字串
		$p = mysqli_real_escape_string($dbc, trim($_POST['pass1']));
	}
	if (empty($errors)) {
		$q = "SELECT user_id FROM users WHERE (email='$em' AND
			  pass=SHA1('$op') )";
		$r = @mysqli_query($dbc, $q);
		$num = mysqli_num_rows($r);
		if ($num == 1) {
			$row = mysqli_fetch_row($r);
			$q = "UPDATE users SET pass=SHA1('$p') WHERE user_id=$row[0]";
			$r = @mysqli_query($dbc, $q);
			if (mysqli_affected_rows($dbc) == 1) {
				echo "<h1>恭喜你</h1><p>你已经成功修改了密码。</p>";
			} else {
				// 没有成功修改
				echo "<h1>系统错误</h1>";
				echo '<p class="error">无法修改密码。</p>';
				echo "<br /><br />"."指令：".mysqli_error($dbc);
			}
			include 'template/footer.php';
			mysqli_close($dbc);
			exit(0);
		} else {
			// 没找到匹配的邮箱
			// 没有成功修改
			echo "<h1>帐号错误</h1>";
			echo '<p class="error">找不到指定的帐号。</p>';
		}
	} else {
		echo "<h1>账户信息不正确</h1>";
		echo '<p class="error">发生了以下错误：</p>';
		foreach ($errors as $e) {
			echo ' - '.$e.'<br />';
		}
		echo "<br />请重试。";

	}
	mysqli_close($dbc);
}

?>
<h1>修改密码</h1>
<form action="password.php" method="post">
	<p>电子邮箱：<input type="text" name="email"
	size="20" maxlength="60" value="<?php if(isset($_POST["email"]))
	echo $_POST["email"];?>" /></p>
	<p>旧密码：<input type="password" name="pass"
	size="10" maxlength="20" /></p>
	<p>新密码：<input type="password" name="pass1"
	size="10" maxlength="20" /></p>
	<p>确认新密码：<input type="password" name="pass2"
	size="10" maxlength="20" /></p>
	<p><input type="submit" name="submit" value="注册"/></p>
</form>
<?php include 'template/footer.php';?>